package com.sniff.atp.provider;

import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @BelongsProject: sniff-atp
 * @BelongsPackage: com.sniff.atp.provider
 * @Author: zxy
 * @CreateTime: 2024-01-26 16:36
 * @Version: 1.0
 */
@Aspect
@Component
public class DataSourceAspect {
    @Pointcut("@annotation(com.sniff.atp.provider.DataSource)")
    public void dataSourcePointCut() {

    }

    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint pjp) {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        DataSource annotation = method.getAnnotation(DataSource.class);

        if (annotation != null) {
            DynamicDataSourceContextHolder.setDataSourceType(annotation.value().name().toLowerCase());
        }
        try {
            return pjp.proceed();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        } finally {
            DynamicDataSourceContextHolder.clearDataSourceType();
        }
    }
}
